package com.newear.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.newear.MyApplication;
import com.newear.R;
import com.newear.bean.WeatherInfo;
import com.newear.constant.DataType;
import com.newear.constant.RequireParams;
import com.newear.happyDialog.CamaraCheckDialog;
import com.newear.message.MessageDispatcher;
import com.newear.message.MessageType;
import com.newear.util.HardWare;
import com.newear.util.MyLogger;
import com.newear.util.T;
import com.newear.util.Validator;

import java.lang.ref.WeakReference;

public class HappyMainActivity extends AppCompatActivity implements AMapLocationListener {
    private static final String TAG = "HappyMainActivity";
    private Context mContext;
    private Activity mActivity;
    private LinearLayout lL_home_face;//面诊
    private LinearLayout lL_home_tongue;//舌诊
    private LinearLayout lL_home_answer;//问诊
    private LinearLayout lL_home_report;//报告

    private Button btn_history;
    private ImageView img_about_new_ear;
    private ImageView img_setting;

    //天气相关
    private TextView tv_main_time;//时间
    private TextView tv_main_week;//星期
    private TextView tv_main_year_day;//年月
    private TextView tv_main_thermometer;//摄氏度描述
    private TextView tv_main_city;//城市
    private TextView tv_main_weather_des;//天气描述

    private ImageView img_main_weather;//天气状况  晴天 多云 阴天 下雨 四种状态
    private ImageView img_main_thermometer;//温度计  小于5°   5°-20° 20°以上 三种状态

    private String key;
    private MyHandler myHandler;
    private static final int UPDATE_TIME_CODE = 1000;
    private static final int UPDATE_TIME = 10 * 1000;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.happy_activity_main);
        init();
        findViews();
        setListeners();
    }

    private void init() {
        this.key = this.hashCode() + "";
        myHandler = new MyHandler(this);
        mContext = this;
        mActivity = this;
        initLocation();
    }


    public void initLocation() {
        mlocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        mlocationClient.setLocationListener(this);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(60 * 60 * 1000);
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.startLocation();

    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                MyLogger.e(TAG, "lat:" + amapLocation.getLatitude() + ",lon:" + amapLocation.getLongitude());
                getWeather(amapLocation.getLatitude(), amapLocation.getLongitude());
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

    private void getWeather(double latitude,double longitude) {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(RequireParams.DATA_TYPE, DataType.GET_WEATHER);
        param.put(RequireParams.MAP_KEY, this.key + DataType.GET_WEATHER);
        param.put(RequireParams.LAT, latitude);
        param.put(RequireParams.LON, longitude);
        param.put(RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    private void findViews(){
        //天气相关
        tv_main_time = (TextView) findViewById(R.id.tv_main_time);
        tv_main_week = (TextView) findViewById(R.id.tv_main_week);
        tv_main_year_day = (TextView) findViewById(R.id.tv_main_year_day);
        tv_main_thermometer = (TextView) findViewById(R.id.tv_main_thermometer);
        tv_main_city = (TextView) findViewById(R.id.tv_main_city);
        tv_main_weather_des = (TextView) findViewById(R.id.tv_main_weather_des);
        img_main_weather = (ImageView) findViewById(R.id.img_main_weather);
        img_main_thermometer = (ImageView) findViewById(R.id.img_main_thermometer);

        lL_home_face = (LinearLayout) findViewById(R.id.lL_home_face);
        lL_home_tongue = (LinearLayout) findViewById(R.id.lL_home_tongue);
        lL_home_answer = (LinearLayout) findViewById(R.id.lL_home_answer);
        lL_home_report = (LinearLayout) findViewById(R.id.lL_home_report);
        //底部
        btn_history = (Button) findViewById(R.id.btn_history);
        img_about_new_ear = (ImageView) findViewById(R.id.img_about_new_ear);
        img_setting = (ImageView) findViewById(R.id.img_setting);
        initTime();
    }

    private void initTime() {
        myHandler.sendEmptyMessage(UPDATE_TIME_CODE);
    }

    private void setListeners() {

        lL_home_face.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (HardWare.isLogined(mContext)) {
                    startActivity(new Intent(HappyMainActivity.this, FaceActivity.class));
                } else {
                    HardWare.gotoLogin(mActivity);
                }
            }
        });

        lL_home_tongue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (HardWare.isLogined(mContext)) {
                    startActivity(new Intent(HappyMainActivity.this, TongueActivity.class));
                } else {
                    HardWare.gotoLogin(mActivity);
                }
            }
        });

        lL_home_answer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //先检测之前的面诊 舌诊是否已完成  之后跳转个人信息页面选择
                if (HardWare.isLogined(mContext)) {
                    if (MyApplication.sCustomerInfo == null || !Validator.isEffective(MyApplication.sCustomerInfo.faceId)) {
                        final CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(mContext, R.style.dialog, "请先完成脸诊！", "再进行问诊", CamaraCheckDialog.Type.FACE);
                        camaraCheckDialog.setOnTakePhotoClickListener(new CamaraCheckDialog.OnTakePhotoClickListener() {

                            @Override
                            public void takePhotoClickListener() {
                                Intent intent = new Intent(HappyMainActivity.this, FaceActivity.class);
                                startActivity(intent);
                            }
                        });
                        camaraCheckDialog.show();
                    } else if (!Validator.isEffective(MyApplication.sCustomerInfo.tongueId)) {
                        final CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(mContext, R.style.dialog, "请先完成舌诊！", "再进行问诊", CamaraCheckDialog.Type.TONGUE);
                        camaraCheckDialog.setOnTakePhotoClickListener(new CamaraCheckDialog.OnTakePhotoClickListener() {

                            @Override
                            public void takePhotoClickListener() {
                                Intent intent = new Intent(HappyMainActivity.this, TongueActivity.class);
                                startActivity(intent);
                            }
                        });
                        camaraCheckDialog.show();
                    } else {
                        Intent intent = new Intent(HappyMainActivity.this, HappyPersonDetailSelectActivity.class);
                        startActivity(intent);
                    }
                } else {
                    HardWare.gotoLogin(mActivity);
                }
            }
        });

        lL_home_report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转报告页面
                if (HardWare.isLogined(mContext)) {
                    if (MyApplication.sCustomerInfo == null || !Validator.isEffective(MyApplication.sCustomerInfo.faceId)) {
                        final CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(mContext, R.style.dialog, "请先完成脸诊！", "再进行问诊", CamaraCheckDialog.Type.FACE);
                        camaraCheckDialog.setOnTakePhotoClickListener(new CamaraCheckDialog.OnTakePhotoClickListener() {

                            @Override
                            public void takePhotoClickListener() {
                                Intent intent = new Intent(HappyMainActivity.this, FaceActivity.class);
                                startActivity(intent);
                            }
                        });
                        camaraCheckDialog.show();
                    } else if (!Validator.isEffective(MyApplication.sCustomerInfo.tongueId)) {
                        final CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(mContext, R.style.dialog, "请先完成舌诊！", "再进行问诊", CamaraCheckDialog.Type.TONGUE);
                        camaraCheckDialog.setOnTakePhotoClickListener(new CamaraCheckDialog.OnTakePhotoClickListener() {

                            @Override
                            public void takePhotoClickListener() {
                                Intent intent = new Intent(HappyMainActivity.this, TongueActivity.class);
                                startActivity(intent);
                            }
                        });
                        camaraCheckDialog.show();
                    } else if (MyApplication.sReportInfo == null){
                        final CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(mContext, R.style.dialog, "请先完成问诊！", "再查看报告", CamaraCheckDialog.Type.REQUESTION);
                        camaraCheckDialog.setOnTakePhotoClickListener(new CamaraCheckDialog.OnTakePhotoClickListener() {

                            @Override
                            public void takePhotoClickListener() {
                                Intent intent = new Intent(HappyMainActivity.this, HappyPersonDetailSelectActivity.class);
                                startActivity(intent);
                            }
                        });
                        camaraCheckDialog.show();
                    } else {
                        Intent intent = new Intent(HappyMainActivity.this, HappyReportActivity.class);
                        startActivity(intent);
                    }
                } else {
                    HardWare.gotoLogin(mActivity);
                }
            }
        });

        //底部跳转
        btn_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转历史记录页面
                if (HardWare.isLogined(mContext)) {
                    Intent intent = new Intent(HappyMainActivity.this, HappyHistoryActivity.class);
                    startActivity(intent);
                } else {
                    HardWare.gotoLogin(mActivity);
                }
            }
        });

        img_about_new_ear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转关于时代页面
                Intent intent = new Intent(HappyMainActivity.this, HappyAboutCompanyActivity.class);
                startActivity(intent);
            }
        });

        img_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转设置界面
                Intent intent = new Intent(HappyMainActivity.this, HappySettingActivity.class);
                startActivity(intent);
            }
        });

    }

    private void updateWeather(WeatherInfo weatherInfo) {
        tv_main_thermometer.setText(weatherInfo.live.temperature + "°C");
        String weather = weatherInfo.live.weather;
        tv_main_weather_des.setText(weather);
        tv_main_city.setText(weatherInfo.live.city);
        int temperature = Integer.parseInt(weatherInfo.live.temperature);
        if (temperature < 5) {
            img_main_thermometer.setBackgroundResource(R.drawable.thermometer_low);
        } else if (temperature < 20) {
            img_main_thermometer.setBackgroundResource(R.drawable.thermometer_middle);
        } else {
            img_main_thermometer.setBackgroundResource(R.drawable.thermometer_high);
        }
        if ("晴".equals(weather)) {
            img_main_weather.setBackgroundResource(R.drawable.weather_sun);
        } else if ("多云".equals(weather)) {
            img_main_weather.setBackgroundResource(R.drawable.weather_cloudy);
        } else if ("阴".equals(weather)) {
            img_main_weather.setBackgroundResource(R.drawable.weather_overcast);
        } else if (Validator.isEffective(weather) && weather.contains("雨")) {
            img_main_weather.setBackgroundResource(R.drawable.weather_rain);
        }
    }

    private void updateTime(String[] timeArr) {
        if (Validator.isEffective(timeArr[0])) {
            tv_main_time.setText(timeArr[0]);
        }
        if (Validator.isEffective(timeArr[1])) {
            tv_main_week.setText(timeArr[1]);
        }
        if (Validator.isEffective(timeArr[2])) {
            tv_main_year_day.setText(timeArr[2]);
        }
        myHandler.sendEmptyMessageDelayed(UPDATE_TIME_CODE, UPDATE_TIME);
    }


    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final HappyMainActivity activity = (HappyMainActivity) mActivityReference.get();
                if (activity != null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.GET_WEATHER) {
                                SparseArray<Object> result = (SparseArray<Object>) msg.obj;
                                String errno = (String) result.get(0);
                                if ("0".equals(errno)) {
                                    WeatherInfo weatherInfo = (WeatherInfo) result.get(1);
                                    if (weatherInfo != null) {
                                        activity.updateWeather(weatherInfo);
                                    }
                                } else if ("1".equals(errno)){
                                    String errMsg = (String) result.get(1);
                                    T.shortToast(activity, errMsg);
                                }
                            }
                            break;
                        case UPDATE_TIME_CODE:
                            String[] nowTime = HardWare.getTime();
                            if (nowTime != null && nowTime.length == 3) {
                                activity.updateTime(nowTime);
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                MyLogger.e(TAG, "handleMessage Exception!e:" + e.getMessage());
            }
        }
    }
}
